package xman.core.component;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class WebAppFilter implements javax.servlet.Filter {
    private static final Logger logger = Logger.getLogger(WebAppFilter.class);
    
    static String suffix = null;
    
    public void destroy() {
    }
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        long startTime = System.currentTimeMillis();
        try {
            chain.doFilter(req, resp);
        } catch (Exception e) {
            return;
        } finally {
            long execTime = System.currentTimeMillis() - startTime;
            StringBuilder sb = new StringBuilder();
            sb.append(execTime);
            sb.append("#").append(request.getRequestURI());
            sb.append("#").append(request.getHeader("User-Agent"));
            sb.append("#").append(request.getHeader("Referer"));
            if (request.getQueryString() != null) {
                sb.append("#").append(request.getQueryString());
            }
            logger.info(sb.toString());
        }
    }
    
    public void init(FilterConfig config) throws ServletException {
        suffix = config.getInitParameter("suffix");
    }
}
